package 代码随想录.哈希;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class a18四数之和 {
    static class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] > target && nums[i] >= 0) break;
                // 去重a
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue;
                }
                for (int j = i + 1; j < nums.length; j++) {
                    int cur = nums[i] + nums[j];
                    if (cur > target && cur >= 0) break;
                    // 去重b
                    if (j > i + 1 && nums[j] == nums[j - 1]) {
                        continue;
                    }
                    int left = j + 1;
                    int right = nums.length - 1;
                    while (left < right) {
                        int sum = nums[i] + nums[j] + nums[left] + nums[right];
                        if (sum > target) {
                            right--;
                        } else if (sum < target) {
                            left++;
                        } else {
                            res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                            // 去重c
                            while (left < right && nums[left] == nums[left + 1]) {
                                left++;
                            }
                            //去重d
                            while (left < right && nums[right] == nums[right - 1]) {
                                right--;
                            }
                            left++;
                            right--;
                        }
                    }
                }
            }
            return res;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {-2,-1,-1,1,1,2,2};
        int target = 0;
        List<List<Integer>> lists = solution.fourSum(nums, target);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}
